package com.dcdata.xian;

import com.dcdata.xian.mapper.GjznCardMapper;
import com.dcdata.xian.mapper.GjznRouteMapper;
import com.dcdata.xian.mapper.GjznStationMapper;
import com.dcdata.xian.pojo.GjznCard;
import com.dcdata.xian.pojo.GjznRoute;
import com.dcdata.xian.pojo.GjznStation;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;


/**
 * @author suxm
 */

public class MysqlOperation {
    /**
     * SQL session.
     */
    private SqlSession sqlSession;
    /**
     * SQL session factory builder.
     */
    private final SqlSessionFactoryBuilder builder;
    /**
     * SQL session factory.
     */
    private SqlSessionFactory sqlSessionFactory;

    private GjznRouteMapper gjznRouteMapper;

    private GjznStationMapper gjznStationMapper;

    private GjznCardMapper gjznCardMapper;

    /**
     * Constructor, initialize SQL session builder.
     */
    public MysqlOperation() {
        builder = new SqlSessionFactoryBuilder();
    }


    /**
     * Connect to database, initialize related mapper.
     */
    public void connectToDatabase() {
        try {
            sqlSessionFactory = builder.build(Resources.getResourceAsStream("SqlMapConfig_xian.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSession = sqlSessionFactory.openSession();

        gjznRouteMapper = sqlSession.getMapper(GjznRouteMapper.class);
        gjznStationMapper = sqlSession.getMapper(GjznStationMapper.class);
        gjznCardMapper = sqlSession.getMapper(GjznCardMapper.class);

    }

    void insertGjznRoute(GjznRoute gjznRoute){
        gjznRouteMapper.insert(gjznRoute);
        sqlSession.commit();
    }

    void insertGjznStation(GjznStation gjznStation){
        gjznStationMapper.insert(gjznStation);
        sqlSession.commit();
    }

    void insertGjznCard(GjznCard gjznCard){
        gjznCardMapper.insert(gjznCard);
        sqlSession.commit();
    }

    /**
     * Close database.
     */
    public void closeDatabase() {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}
